<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <!-- <el-form-item label="地址名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入地址名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <!-- <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button> -->
         <el-button type="primary" icon="el-icon-plus"  @click="add(1)">新增父级地址</el-button>
        <el-button type="primary" icon="el-icon-plus"   @click="add(2)">新增子级地址</el-button>
      </el-form-item>
    </el-form>
           
<!-- 列表   @row-click="nodeClick" -->
    <el-table :data="deptList"  ref="tableData"
            row-key="id"  
            lazy 
            :load="loadNode" 
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
             @selection-change="handleSelectionChange"
          >
      <el-table-column type="selection" width="55" />
      <el-table-column  label="地址" prop="name" ></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button  type="text"  icon="el-icon-edit"  @click="handleUpdate(scope.row)">修改</el-button>
          <!-- <el-button  v-if="scope.row.parentId != 0"  type="text"  icon="el-icon-delete"  @click="handleDelete(scope.row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :closeOnClickModal="false" >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
           <el-col :span="24" v-if="this.fName == true">
            <el-form-item label="父节点">
              <el-input v-model="parentName" placeholder="无父节点" disabled style="width:50%;"/>
            </el-form-item>
            <!-- <el-form-item label="父节点">
              <el-input v-model="parentName" placeholder="无父节点" disabled/>
            </el-form-item> -->
          </el-col>
          <el-col :span="24">
            <el-form-item label="地址名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入地址名称" style="width:80%;"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm"  v-if=" this.fName == true" icon="el-icon-finished">确 定</el-button>
        <el-button type="primary" @click="submitUpdate" v-if=" this.fName == false" icon="el-icon-finished">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

// import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Dept",
  components: { Treeselect },
  data() {
    return {
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        name: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // pid: [
        //   { required: true, message: "上级地址不能为空", trigger: "blur" }
        // ],
        // name: [
        //   { required: true, message: "地址名称不能为空", trigger: "blur" }
        // ],
      },
      pid:0,
      multipleSelection: [],
      parentName:'',//父节点名称
      fName:true,

    };
  },
  created() {
    this.getList();
    this.loadNode()
  },
  methods: {
    /** 查询部门列表 */
    getList() {
      const _self =this
      this.axios.post('/monitor/Sys/dept/getpid?pid=0').then(res => {
        this.deptList = res.data.data;
        this.deptList.forEach(e=>{
          e.hasChildren=true
        })
        console.log(res,'res-列表返回')
      });
    },

    loadNode(tree, treeNode, resolve) {
      var that=this
      this.pid = tree.id
      this.dg()
      // if(treeNode.level==0){
      //     return resolve(that.deptList)
      // }
      if(tree.children){
        
      }
      setTimeout(()=>{
          resolve(tree.children);
      },500)
      console.log('懒加载tree',tree);
      console.log('懒加载treeNode',treeNode);
      console.log('懒加载resolve',resolve);
      // this.axios.post('/monitor/Sys/dept/getpid?pid='+this.pid).then(res=>{
      //   // resolve(res.data.data);
      //     // this.deptList = res.data.data
      // })
    },

    nodeClick(data){//点击展开子集
      console.log(data,'点击表格data');
      this.pid = data.id
      this.dg()
      this.loadNode()
    },
    dg(){
      if(this.pid!=0){
          this.axios.post('/monitor/Sys/dept/getpid?pid='+this.pid).then(res=>{
              if(res.status==200){
                  var children=res.data.data
                  children.forEach(e=>{
                    e.hasChildren=true
                  })
                  this.foreachFunc(this.deptList,children)
              }else{
                  alert(res.data.msg)
              }
          })
      }
    },
    foreachFunc(arr,children){
        var that=this
        console.log(arr)
        arr.forEach(function(e,index){
            if(e.id==that.pid){
                e.children=children
            }else{
                that.foreachFunc(e.children,children)
            }
        })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        pid: undefined,
        name: undefined,
      };
      // this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      this.handleQuery();
    },
    // 选中
    handleSelectionChange(val) {
      if(val.length>1){//1次选一个，清空上一个，切换选中项
        this.$refs.tableData.clearSelection()
        this.$refs.tableData.toggleRowSelection(val.pop())
        this.multipleSelection =[]
      }
      this.multipleSelection = val//没有
      console.log(val,this.multipleSelection,'vvv')
    },

    /** 新增按钮操作 */
    add(index) {
      this.reset();
      this.parentName = ''
      this.fName = true
      if (index === 1) {
        if (this.multipleSelection.length >= 1) {
          this.$message({
            message: '请勿选择节点进行操作'
          })
          return
        }
        this.form={
            pid:0,
            parentName:undefined,
        }
      }else if (index === 2) {
          if (this.multipleSelection.length === 0) {
            this.$message({
              message: '请选择父节点'
            })
            return
          }
          this.form={//显示父节点
              pid:this.multipleSelection[0].id,
          }
          this.parentName = this.multipleSelection[0].name
      } 
      this.open = true;
      this.title = "添加地址";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // console.log(this.multipleSelection[0],'this.multipleSelection[0]');
      // this.parentName = this.multipleSelection[0].name//父节点名称展示
      this.form = row
      this.open = true;
      this.fName = false//父级显示
      this.title = "修改地址";
      console.log(row,'编辑');
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
            console.log(this.form,'新增');
            this.axios({url:'monitor/Sys/dept/save',method:'post',data:this.form,}).then(res => {
              this.$message({ type: "success", message: "新增成功!",});
              this.open = false;
              this.getList();
            });
        }
      });
    },
    submitUpdate: function() {//修改-确定按钮
      this.$refs["form"].validate(valid => {
        if (valid) {
        console.log(this.form,'修改');              
        this.axios({url:'monitor/Sys/dept/update',method:'post',data:this.form,}).then(res => {
          this.$message({ type: "success", message: "修改成功!",});
          this.open = false;
          this.getList();
        });
        }
      });
    },
    
  }
};
</script>
<style >
  .el-input.is-disabled .el-input__inner{
    color: black !important;
  }
</style>